<?php defined('SYSPATH') or die('No direct script access.');

class Model_Log extends ORM
{  
    protected $_table_name = 'logs';
    protected $_reload_on_wakeup = false;
    
    const TYPE_STATUS   = 'status';
    const TYPE_ASSIGNED = 'assigned';
    
    public static function get_available_types()
    {
        return array(self::TYPE_STATUS, self::TYPE_ASSIGNED);
    }
    
    public function get_logs(Model_Ticket $ticket)
    {
        return $this->_get_logs_query()
                    ->where('ticket_id', '=', $ticket->id)
                    ->order_by('created', 'DESC')
                    ->find_all()
                    ->as_array();        
    }
    
    protected function _get_logs_query()
    {
        return ORM::factory('log');
    }
    
    public function add_log(Model_Ticket $ticket, $type, $value)
    {
        $user_id = 0;
        $user = Model_Auth::instance()->get_user();
        if ($user) {
            $user_id = $user->id;   
        }
        
        if (!in_array($type, self::get_available_types())) {
            throw new Model_Exception('Некорректный тип');
        }
        
        $mailbox = ORM::factory('mailbox', $ticket->mailbox_id);
        $company = Model_Main::get_company();
        if ($company->id != $mailbox->company_id) {
            throw new HTTP_Exception_404('Такой компании нет');    
        }
        
        $this->ticket_id    = $ticket->id;
        $this->user_id      = $user_id;
        $this->type         = $type;
        $this->value        = $value;
        $this->created      = time();       
        $this->save();
        
        return $this;  
    }
}
